/*! Invoice flow: same as之前版本，省略注释，功能不变（启用按钮→弹窗→提交→更新行内状态） */
(function(){
  const $$ = (s, c=document) => Array.from(c.querySelectorAll(s));
  const $  = (s, c=document) => c.querySelector(s);
  function ready(f){ if(document.readyState!=='loading') f(); else document.addEventListener('DOMContentLoaded', f); }
  function normalizeAmount(t){ const m=String(t||'').replace(/[^\d\.\-]/g,''); const v=parseFloat(m||'0'); return isNaN(v)?0:v; }
  function createModal(){
    if($('#rtinv-overlay')) return $('#rtinv-overlay');
    const wrap=document.createElement('div');
    wrap.id='rtinv-overlay'; wrap.className='rtinv-overlay';
    wrap.innerHTML=`<div class="rtinv-modal" role="dialog" aria-modal="true" aria-labelledby="rtinv-title">
      <div class="rtinv-hd"><h3 id="rtinv-title">申请发票 Apply Invoice</h3><button class="rtinv-close" id="rtinv-close" aria-label="关闭 Close">×</button></div>
      <div class="rtinv-bd">
        <p class="rtinv-order" id="rtinv-order"></p>
        <div class="rtinv-tabs" role="tablist" aria-label="选择开票主体">
          <button class="rtinv-tab" role="tab" aria-selected="true" id="rtinv-tab-cn" aria-controls="rtinv-panel-cn">中国公司开票</button>
          <button class="rtinv-tab" role="tab" aria-selected="false" id="rtinv-tab-us" aria-controls="rtinv-panel-us">US Company Invoice</button>
        </div>
        <div class="rtinv-success" id="rtinv-success">提交成功。我们已收到您的申请并将尽快处理。</div>
        <form class="rtinv-form active" id="rtinv-panel-cn" data-region="cn" novalidate>
          <div class="rtinv-fields">
            <div><label>发票抬头（公司）</label><input required name="title" placeholder="请输入公司全称"/></div>
            <div><label>统一社会信用代码</label><input required name="taxNo" placeholder="18位或20位" pattern="[A-Z0-9\\-]{15,20}"/><div class="rtinv-hint">支持15–20位字母数字。</div></div>
            <div><label>发票类型</label><select name="type"><option value="normal">增值税普通发票</option><option value="special">增值税专用发票</option></select></div>
            <div><label>开票内容</label><select name="content"><option value="software_service">软件服务</option><option value="copyright_fee">版权费</option><option value="technical_service">技术服务费</option></select></div>
            <div><label>收票邮箱</label><input required type="email" name="email" placeholder="name@example.com"/></div>
            <div><label>收票手机号</label><input required name="mobile" placeholder="11位中国大陆手机号" pattern="^1[3-9]\\d{9}$"/></div>
            <div class="full"><label>公司地址</label><input name="addr" placeholder="选填"/></div>
            <div><label>开户行</label><input name="bank" placeholder="选填"/></div>
            <div><label>银行账号</label><input name="bankAccount" placeholder="选填"/></div>
            <div class="full"><label>备注说明</label><textarea name="memo" rows="2" placeholder="选填"></textarea></div>
            <div><label>开票金额（¥）</label><input name="amount" id="rtinv-cn-amount" readonly/></div>
            <div><label>订单号</label><input name="orderId" id="rtinv-cn-order" readonly/></div>
          </div>
          <div class="rtinv-err" id="rtinv-cn-err">请检查必填项是否完整且格式正确。</div>
          <div class="rtinv-actions"><button type="button" class="rtinv-btn ghost" data-action="cancel">取消</button><button type="submit" class="rtinv-btn primary">提交申请</button></div>
        </form>
        <form class="rtinv-form" id="rtinv-panel-us" data-region="us" novalidate>
          <div class="rtinv-fields">
            <div><label>Company Name</label><input required name="company" placeholder="Legal entity name"/></div>
            <div><label>EIN / Tax ID (optional)</label><input name="ein" placeholder="##-#######"/></div>
            <div class="full"><label>Billing Address</label><input required name="address1" placeholder="Street, Unit"/></div>
            <div><label>City</label><input required name="city"/></div>
            <div><label>State</label><input required name="state"/></div>
            <div><label>ZIP</label><input required name="zip"/></div>
            <div><label>Contact Email</label><input required type="email" name="email"/></div>
            <div><label>Contact Phone</label><input name="phone" placeholder="+1 555 000 0000"/></div>
            <div class="full"><label>Invoice Memo</label><textarea name="memo" rows="2" placeholder="Optional"></textarea></div>
            <div><label>Amount (USD)</label><input name="amount" id="rtinv-us-amount" readonly/></div>
            <div><label>Order ID</label><input name="orderId" id="rtinv-us-order" readonly/></div>
          </div>
          <div class="rtinv-err" id="rtinv-us-err">Please fill all required fields with valid values.</div>
          <div class="rtinv-actions"><button type="button" class="rtinv-btn ghost" data-action="cancel">Cancel</button><button type="submit" class="rtinv-btn primary">Submit</button></div>
        </form>
      </div></div>`;
    document.body.appendChild(wrap);
    $('#rtinv-close').addEventListener('click', ()=>wrap.classList.remove('show'));
    wrap.addEventListener('click',(e)=>{ if(e.target===wrap) wrap.classList.remove('show'); });
    document.addEventListener('keydown',(e)=>{ if(e.key==='Escape') wrap.classList.remove('show'); });
    const tabCN=$('#rtinv-tab-cn'), tabUS=$('#rtinv-tab-us');
    const formCN=$('#rtinv-panel-cn'), formUS=$('#rtinv-panel-us');
    function setTab(w){ const cn=w==='cn'; tabCN.setAttribute('aria-selected', cn?'true':'false'); tabUS.setAttribute('aria-selected', cn?'false':'true'); formCN.classList.toggle('active',cn); formUS.classList.toggle('active',!cn); }
    tabCN.addEventListener('click',()=>setTab('cn')); tabUS.addEventListener('click',()=>setTab('us'));
    $$('[data-action="cancel"]',wrap).forEach(b=>b.addEventListener('click',()=>wrap.classList.remove('show')));
    return wrap;
  }
  function showModal(order){
    const o=createModal(); o.classList.add('show');
    $('#rtinv-order').textContent=`订单号 ${order.id} · 金额 ${order.amountText}`;
    $('#rtinv-cn-amount').value=order.amountCN; $('#rtinv-cn-order').value=order.id;
    $('#rtinv-us-amount').value=order.amountUS; $('#rtinv-us-order').value=order.id;
    (/¥|CN¥|CNY/i.test(order.amountText)?document.getElementById('rtinv-tab-cn'):document.getElementById('rtinv-tab-us')).click();
  }
  function getRowOrderInfo(btn){
    const tr=btn.closest('tr'); const tds=tr?Array.from(tr.querySelectorAll('td')):[];
    const id=tds[0]?.textContent.trim()||''; const amountText=tds[1]?.textContent.trim()||'';
    const payMethod=tds[2]?.textContent.trim()||''; const payTime=tds[3]?.textContent.trim()||'';
    const amt=normalizeAmount(amountText); return { id, amountText, amountCN:String(amt), amountUS:String(amt), payMethod, payTime, row:tr, tds };
  }
  function setAppliedUI(order){
    try{
      const statusCell=order.tds[4]; if(statusCell){ const badge=statusCell.querySelector('.rtacc-badge')||statusCell.firstElementChild||statusCell; badge.classList.add('success'); badge.textContent='已申请'; }
      const opCell=order.tds[5]; if(opCell){ const btn=opCell.querySelector('button,a'); if(btn){ btn.disabled=true; btn.classList.remove('primary'); btn.textContent='已申请'; btn.setAttribute('aria-disabled','true'); } }
    }catch(e){}
  }
  async function submitInvoice(region, data){
    const payload={ region, ...data, timestamp:new Date().toISOString(), userAgent:navigator.userAgent };
    const apiBase=window.RuotongConfig && window.RuotongConfig.invoiceApi;
    if(apiBase){
      try{
        const res=await fetch(String(apiBase).replace(/\/$/,'')+'/apply',{ method:'POST', headers:{'Content-Type':'application/json'}, credentials:'include', body:JSON.stringify(payload)});
        if(res.ok) return {ok:true, via:'api', data: await res.json().catch(()=>({}))};
      }catch(e){ console.warn('[invoice] API fallback:',e); }
    }
    try{ const k='rt-invoices'; const arr=JSON.parse(localStorage.getItem(k)||'[]'); arr.push(payload); localStorage.setItem(k, JSON.stringify(arr)); return {ok:true, via:'localStorage'}; }
    catch(e){ return {ok:false, error:e}; }
  }
  function validate(form){ if(!form) return false; if(!form.checkValidity()) return false; if(form.getAttribute('data-region')==='cn'){ const tax=form.querySelector('[name="taxNo"]'); if(tax && tax.value && !/^[A-Z0-9-]{15,20}$/i.test(tax.value.trim())) return false; } return true; }
  function connectForms(currentOrder){
    const overlay=$('#rtinv-overlay'), cnForm=$('#rtinv-panel-cn'), usForm=$('#rtinv-panel-us');
    const cnErr=$('#rtinv-cn-err'), usErr=$('#rtinv-us-err'), succ=$('#rtinv-success');
    function onSubmit(region,e){ e.preventDefault(); const form=region==='cn'?cnForm:usForm; const err=region==='cn'?cnErr:usErr; err.classList.remove('show'); succ.classList.remove('show');
      if(!validate(form)){ err.classList.add('show'); return; }
      const obj=Object.fromEntries(new FormData(form).entries());
      obj.orderId=currentOrder.id; obj.orderAmountText=currentOrder.amountText; obj.payMethod=currentOrder.payMethod; obj.payTime=currentOrder.payTime;
      submitInvoice(region, obj).then(r=>{ if(r.ok){ succ.textContent='申请已提交成功，我们会尽快处理。'; succ.classList.add('show'); setAppliedUI(currentOrder); setTimeout(()=>overlay.classList.remove('show'), 900);} else { err.textContent='提交失败，请稍后重试。'; err.classList.add('show'); }});
    }
    cnForm.addEventListener('submit', onSubmit.bind(null,'cn'));
    usForm.addEventListener('submit', onSubmit.bind(null,'us'));
  }
  function enableButtons(){
    const invoiceSection=document.getElementById('invoice'); if(!invoiceSection) return;
    const btns=$$('button, a',invoiceSection).filter(el=>/申请发票/.test(el.textContent.trim()));
    btns.forEach(btn=>{ btn.disabled=false; btn.removeAttribute('aria-disabled'); btn.classList.add('js-apply-invoice');
      btn.addEventListener('click',(e)=>{ e.preventDefault(); const info=getRowOrderInfo(btn); showModal(info); connectForms(info); }); });
  }
  ready(function(){
    enableButtons();
    if(location.hash==='#invoice'){ const invTab=(document.querySelector('button.tab[data-target="#invoice"]')||document.querySelector('[href="#invoice"]')); if(invTab && invTab.getAttribute('aria-selected')!=='true'){ invTab.click(); } }
  });
})();


// === Added by build: invoice eligible sum + batch apply ===
(function(){
  function parseCNY(text){
    if(!text) return 0;
    const n = (text.replace(/[^0-9.]/g,'') || '0');
    return parseFloat(n) || 0;
  }
  function refreshEligibleSum(){
    const box = document.getElementById('rtacc-invoice-eligible');
    if(!box) return;
    const rows = Array.from(document.querySelectorAll('#invoice .rtacc-table tbody tr'));
    let sum = 0;
    rows.forEach(tr=>{
      const status = (tr.querySelector('[data-col="status"]')?.innerText || tr.cells[4]?.innerText || '').trim();
      const amountText = (tr.querySelector('[data-col="amount"]')?.innerText || tr.cells[1]?.innerText || '').trim();
      if(/未申请|可开票|未开票/.test(status)){
        sum += parseCNY(amountText);
      }
    });
    box.innerText = sum.toLocaleString(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 });
  }
  function applyBatchInvoice(){
    const rows = Array.from(document.querySelectorAll('#invoice .rtacc-table tbody tr'));
    rows.forEach(tr=>{
      const btn = tr.querySelector('[data-action="apply-invoice"], .rtacc-btn.primary, .rtacc-btn');
      const statusCell = tr.querySelector('[data-col="status"]') || tr.cells[4];
      if(statusCell && /未申请|可开票|未开票/.test(statusCell.innerText)){
        if(btn && !/disabled/.test(btn.getAttribute('disabled')||'')){
          btn.click();
        }else{
          statusCell.innerHTML = '<span class="rtacc-badge success">已申请</span>';
        }
      }
    });
    setTimeout(refreshEligibleSum, 50);
  }
  document.addEventListener('DOMContentLoaded', function(){
    refreshEligibleSum();
    const btn = document.getElementById('rtacc-invoice-batch');
    if(btn){
      btn.addEventListener('click', function(){
        applyBatchInvoice();
      });
    }
  });
  window.addEventListener('storage', function(e){
    if((e.key||'').includes('invoice')) refreshEligibleSum();
  });
  setInterval(refreshEligibleSum, 1000);
})();
// === End addon ===
